<template>
    <div class="chat-container">
      <div v-if="messages.length == 0" class="welcome-message">
      <h3 class="welcome-title">我是数据分析成果大脑，很高兴见到您！</h3>
      <h5 class="welcome-subtitle">我可以帮你数据智能分析、深度挖掘、为灾害预测、应急响应和调度规划提供建议和技术支持，请把你的任务交给我吧~</h5>
    </div>
      <el-scrollbar ref="scroll" class="messages-box">
        <div v-for="(msg, index) in messages" 
             :key="index"
             :class="['message', msg.role]">
          <el-card shadow="hover">
            <div class="message-header">
              <el-tag :type="msg.role === 'user' ? 'primary' : 'success'">
                {{ msg.role === 'user' ? '您' : '助手' }}
              </el-tag>
            </div>
            <formatted-content :content="msg.content" />
          </el-card>
        </div>
        <div v-if="loading" class="loading-indicator">
          <i class="el-icon-loading"></i> 正在生成...
        </div>
      </el-scrollbar>
      <div class="input-area">
  <el-row type="flex" align="middle">
    <!-- 输入框区域 -->
    <el-col :span="24">
      <div class="input-with-buttons">
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="3"
          placeholder="输入您的问题..."
          @keydown.enter.native.prevent="sendMessage"
          class="input-box"
        />
        <!-- 按钮容器 -->
        <div class="inner-buttons">
          <el-button
            type="primary"
            :loading="loading"
            @click="sendMessage"
            size="small"
            class="send-btn">
            发送
          </el-button>
          <el-button
            type="danger"
            @click="stopMessage"
            size="small"
            class="stop-btn">
            停止
          </el-button>
        </div>
      </div>
    </el-col>
  </el-row>
</div>
    </div>
  </template>
  
  <script lang="ts">
  import { Component, Mixins, Ref,Prop } from 'vue-property-decorator';
  import StreamHandler  from '@/utils/LocalStreamHandler';
  import FormattedContent from '@/views/app/components/FormattedContent.vue';
  
  @Component({
    components: { FormattedContent }
  })
  export default class ChatWindow extends Mixins(StreamHandler) {
    @Ref() readonly scroll!: any;
    @Prop() answerMap;

    private streamDataHandler!: (chunk: string) => void;
    private streamErrorHandler!: (err: Error) => void;
    messages: Array<{ role: string; content: string }> = [];
    inputText = '';
    loading = false;
    currentAnswer = '';
    data = false;
  
    async sendMessage() {
      if (!this.inputText.trim() || this.loading) return;
  
      this.loading = true;
      this.messages.push({ role: 'user', content: this.inputText });
      this.messages.push({ role: 'assistant', content: '' });
      
      this.$nextTick(() => this.scrollToBottom());
      
      this.currentAnswer = '';
      let findText = this.inputText;
      this.inputText = '';
      
      if(this.data){
        findText +="基于下面的数据进行分析并输出使用echart 渲染图表，并生成 可执行html 数据为：" + JSON.stringify(this.data);
      }
      for (const item of this.answerMap) {
        if (findText.includes(item.name)) {
          findText  = findText.replace(item.name,item.value);
          break; // 匹配到后立即退出循环
        }
      }
      console.log(findText)

      const request = {
          query: findText,
          response_mode: "streaming",
          user: "user-123",
        };
      //await this.fetchStream(findText);
      await this.fetchLocalStream(request);
      this.stopMessage();
  
    }
  
    scrollToBottom() {
      if(this.scroll.wrap$ &&  this.scroll.wrap$.scrollHeight){
        this.scroll.wrap$.scrollTop = this.scroll.wrap$.scrollHeight;
      }
    }

    private handleStreamData(chunk: string) {
        const newContent = this.currentAnswer + chunk;
        
        // 正确更新方式：替换整个消息对象
        this.messages = [
            ...this.messages.slice(0, -1),
            {
            role: 'assistant',
            content: newContent
            }
        ];
        this.currentAnswer = newContent;
        console.log(this.messages)
        this.scrollToBottom();

    }

    private handleStreamError(err){
        this.$message.error(`请求失败: ${err.message}`);
        this.loading = false;
    }
  
    mounted() {
    
        this.streamDataHandler = (chunk: string) => this.handleStreamData(chunk);
        this.streamErrorHandler = (err: Error) => this.handleStreamError(err);
        this.$on('stream-data', this.streamDataHandler);
        this.$on('stream-error', this.streamErrorHandler);

        (this as any).$bus.$on('data',data =>{
          this.data = data;
        });
    }
  
    beforeDestroy() {
        this.$off('stream-data', this.streamDataHandler);
        this.$off('stream-error', this.streamErrorHandler);
       this.abortStream();
    }

    stopMessage(){
       
        this.abortStream();
        this.loading = false;
    }
  }
  </script>
  
  <style scoped lang="scss">
  .chat-container {
    height: 90vh;
    display: flex;
    flex-direction: column;
   
    background:url(~@/assets/image/banner-background.png) center center no-repeat; 
    /* 新增欢迎信息样式 */
  .welcome-message {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 20px;
    height: 100%;

    .welcome-title {
      color: #1a73e8; /* 主标题蓝色 */
      font-size: 24px;
      margin-bottom: 16px;
      font-weight: 500;
    }

    .welcome-subtitle {
      color: #606266; /* 副标题深灰色 */
      font-size: 16px;
      line-height: 1.6;
      max-width: 600px;
      opacity: 0.9;
    }
  }
  
.messages-box {
      flex: 1;
      padding: 20px;
  
      .message {
        margin-bottom: 16px;
  
        &.user {
          margin-left: 20%;
          .el-card {
            background: #f0f7ff;
          }
        }
  
        &.assistant {
          margin-right: 20%;
          .el-card {
            background: #f5f7fa;
          }
        }
  
        .message-header {
          margin-bottom: 8px;
        }
      }
  
      .loading-indicator {
        text-align: center;
        color: #909399;
        padding: 10px;
      }
    }
}

/* 容器定位 */
.input-with-buttons {
  position: relative;  /* 关键：为按钮定位提供基准 */
}

/* 输入框样式 */
.input-box {
  padding-right: 120px !important; /* 给右侧按钮预留空间 */
  ::v-deep .el-textarea__inner {
    resize: vertical;  /* 允许垂直调整高度 */
  }
}

/* 内部按钮容器 */
.inner-buttons {
  position: absolute;
  right: 10px;
  bottom: 10px;
  z-index: 2;  /* 确保按钮在输入框上方 */
  display: flex;
  gap: 8px;    /* 按钮间距 */
  
  /* 适配输入框高度变化 */
  transition: bottom 0.2s;
}

/* 当输入框高度变化时微调按钮位置 */
::v-deep .el-textarea__inner:focus {
  & + .inner-buttons {
    bottom: 12px;  /* 聚焦时微调位置 */
  }
}

/* 按钮悬停效果 */
.inner-buttons .el-button {
  opacity: 0.9;
  transition: opacity 0.2s;
  &:hover {
    opacity: 1;
    transform: translateY(-1px);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .inner-buttons {
    right: 6px;
    bottom: 6px;
    gap: 6px;
  }
  
  .input-box {
    padding-right: 100px !important;
  }
  
  .inner-buttons .el-button {
    padding: 8px 12px;
  }
}
  </style>